<?php

require "../utility.php";

function genSessionID(string $user_name): string {
    $timestamp = time();
    $session_id = md5("$timestamp$user_name");

    return $session_id;
}

function storeSessionIdToDB(mysqli $conn, string $session_id, string $user_id): bool {
    $insert_str = "INSERT INTO Session (ID, userID) VALUES(?, ?) ON DUPLICATE KEY  UPDATE ID = ?;";
    $insert_stmt = $conn->prepare($insert_str);
    $insert_stmt->bind_param("sis", $session_id, $user_id, $session_id);
    $status = $insert_stmt->execute();
    return $status;
}

$json = getJsonDataFromRawInput();

http_response_code(403);

if (check_keys($json, "user_name", "passwd", "permission")) {
    $user_name = $json["user_name"];
    $passwd = $json["passwd"];
    $required_permission = $json["permission"];

    $query_str = "SELECT passwd, ID FROM User WHERE userName = '$user_name';";
    $conn = connect_mysql();
    $query = $conn->query($query_str);
    if ($user_info = $query->fetch_row()) {
        $passwd_in_db = $user_info[0];
        $user_id = $user_info[1];
        $user_permission = getUserPermissionByUserId($conn, $user_id);
        if ((int)$user_permission >= (int)$required_permission && $passwd === $passwd_in_db) {
            // 生成 session ID
            $session_id = genSessionID($user_name);
            if (storeSessionIdToDB($conn, $session_id, $user_id)) {
                // success
                http_response_code(200);
                
                echo $session_id;
            } else {
                http_response_code(500);
            }
        }
    }
    $query->close();
    $conn->close();
}

?>